﻿using System.Windows;
using System.Windows.Controls;

namespace XamlingCore.SL.Controls.Buttons
{
    [TemplateVisualState(GroupName="ToggledStates", Name="Unchecked")]
    [TemplateVisualState(GroupName = "ToggledStates", Name = "Checked")]
    [TemplateVisualState(GroupName = "ToggledStates", Name = "Middle")]
    public class XToggleButton : Button
    {

        public XToggleButton()
        {
            
        }
        public bool IsChecked
        {
            get { return (bool)GetValue(IsCheckedProperty); }
            set { SetValue(IsCheckedProperty, value); }
        }



        public bool IsThirdState
        {
            get { return (bool)GetValue(IsThirdStateProperty); }
            set { SetValue(IsThirdStateProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsThirdState.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsThirdStateProperty =
            DependencyProperty.Register("IsThirdState", typeof(bool), typeof(XToggleButton), new PropertyMetadata(false, doChecked));

        public override void OnApplyTemplate()
        {
            updateVisualStates(false);
            base.OnApplyTemplate();
        }


        private void ChangeCheckedState()
        {
            updateVisualStates(true);
        }

        void updateVisualStates(bool useTrans)
        {
            if (IsThirdState)
            {
                VisualStateManager.GoToState(this, "Middle", useTrans);
            }
            else
            {
                if (IsChecked)
                {
                    VisualStateManager.GoToState(this, "Checked", useTrans);
                }
                else
                {
                    VisualStateManager.GoToState(this, "Unchecked", useTrans);
                }
            }
            
            
        }

        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsCheckedProperty =
            DependencyProperty.Register("IsChecked", typeof(bool), typeof(XToggleButton), new PropertyMetadata(false, doChecked));

        private static void doChecked(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var item = d as XToggleButton;
            if(item!=null)
            {
                item.ChangeCheckedState();
            }
        }

       
    }
}
